import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider, WeaTop, WeaTab, WeaLeftRightLayout, WeaLeftTree, WeaFormItem, WeaSearchGroup, WeaRightMenu, WeaErrorPage } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { Button, Form } from 'antd';
import HighSeasDispenseDialog from '../dialog/HighSeasDispenseDialog';
import HighSeasLogDialog from '../dialog/HighSeasLogDialog';

@inject('highSeasListStore')
@observer
class HighSeasList extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { highSeasListStore } = this.props;
    highSeasListStore.initDatas();
  }

  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { highSeasListStore } = nextProps;
      highSeasListStore.initDatas();
    }
  }


  render() {
    const { highSeasListStore } = this.props;
    const { showLeft, treeData, counts, countsType, applySuccessNum, tableStore, loading, showSearchAd, searchConditionForm, searchBaseParams, rightMenu, logDialogVisible, logType } = highSeasListStore;

    return (
      <div>
        <WeaRightMenu
          ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@0kq0fh`}
          datas={this.getRightMenus()}
          onClick={this.onRightMenuClick.bind(this)}
          collectParams={{
            favname: getLabel(385464, '客户公海'),
            favouritetype: 4,
            importantlevel: 1,
            objid: -1,
          }}
        >
          <WeaTop
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@obbo9u`}
            title={getLabel(385464, '客户公海')}
            icon={<i className="icon-coms-crm" />}
            iconBgcolor="#96358a"
            buttons={this.getButtons(this.props.ecId || '')}
            loading={loading}
            buttonSpace={10}
            dropMenuDatas={this.getRightMenus()}
          >
            <WeaLeftRightLayout
              ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@gn2bhf`}
              leftWidth={240}
              leftCom={
                <div style={{ height: '100%' }}>
                  <WeaLeftTree
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@v3u2v4`}
                    searchLabel={getLabel(387161, '全部公海')}
                    datas={treeData.slice()}
                    countsType={countsType.slice()}
                    counts={toJS(counts)}
                    onSelect={((ids, nodeids, nodes, event) => {
                      highSeasListStore.resetParams();
                      highSeasListStore.seasId = ids;
                      highSeasListStore.doSearch();
                    })}
                  />

                </div>}
              onCollapse={showLeft => highSeasListStore.isShowLeft(showLeft)}
              showLeft={showLeft}
            >
              <WeaTab
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@n4ncgf`}
                searchType={['base', 'advanced']}
                keyParam="viewcondition" // 主键
                searchsBaseValue={(searchBaseParams && searchBaseParams.name) || ''}
                onSearchChange={v => highSeasListStore.setSearchKey(v)}
                showSearchAd={showSearchAd}
                buttonsAd={this.getAdButtons(highSeasListStore, this.props.ecId || '')}
                setShowSearchAd={bool => highSeasListStore.setShowSearchAd(bool)}
                hideSearchAd={() => highSeasListStore.setShowSearchAd(false)}
                searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@0w5fn9`} horizontal>{this.getSearchConditionForm(highSeasListStore)}</Form>}
                onSearch={highSeasListStore.doSearch}
              />
              <WeaTable
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@hqny4l`}
                comsWeaTableStore={tableStore}
                hasOrder
                needScroll
                loading={loading}
                getColumns={columns => this.getColumns(columns)}
              />
            </WeaLeftRightLayout>
          </WeaTop>
          <HighSeasDispenseDialog ecId={`${this && this.props && this.props.ecId || ''}_HighSeasDispenseDialog@azkvux`} contentStore={highSeasListStore} />
        </WeaRightMenu>
        {logDialogVisible && <HighSeasLogDialog ecId={`${this && this.props && this.props.ecId || ''}_HighSeasLogDialog@8hifk8`} contentStore={highSeasListStore} logType={highSeasListStore.logType} />}
      </div>
    );
  }

  getRightMenus() {
    const { highSeasListStore } = this.props;
    const { rightMenu, tableStore } = highSeasListStore;
    const { selectedRowKeys } = tableStore;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    const btnArr = [];
    rightMenu && rightMenu.map((m) => {
      btnArr.push({
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        disabled: (m.isControl == '1' && isDisabled),
      });
    });
    return btnArr;
  }

  getAdButtons(store, ecId) {
    const { doSearch, setShowSearchAd, clearAdFields } = store;
    return [
      (<Button ecId={`${ecId}_Button@5cqqlb@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${ecId}_Button@6dovht@reset`} type="ghost" onClick={() => { clearAdFields(); }}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${ecId}_Button@w3rcoj@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }

  getSearchConditionForm(store) {
    const { searchConditionComponents, searchConditionForm } = store;
    const groups = [];
    if (searchConditionComponents) {
      const { isFormInit } = searchConditionForm;
      const formParams = searchConditionForm.getFormParams();
      isFormInit && toJS(searchConditionComponents).map((c, i) => {
        const items = [];
        c.items.map((fields, index) => {
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ptmzvm@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1iu2bb@${fields.domkey[0]}`} fieldConfig={fields} form={searchConditionForm} formParams={formParams} onChange={store.searchConditionFieldChange} onEnterSearch={this.onEnterSearch} />
            </WeaFormItem>),
            col: 2,
          });
        });
        groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@788ofc@${i}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
    }
    return groups;
  }

  onRightMenuClick(key) {
    const { highSeasListStore } = this.props;
    const { rightMenu, tableStore } = highSeasListStore;
    const { selectedRowKeys } = tableStore;
    rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
      if (Number(key) == i) {
        const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
        if (m.type == 'BTN_APPLY_CUSTOMER') {
          // highSeasListStore.controlOperateDialog(true,"add",fn );
          highSeasListStore.applyCustomer(selectedRowKeys);
        } else if (m.type == 'BTN_LOG') {
          highSeasListStore.showLog();
        }
      }
    });
  }


  getButtons(ecId) {
    const { highSeasListStore } = this.props;
    const { tableStore, rightMenu } = highSeasListStore;
    const { selectedRowKeys } = tableStore;
    const btnArr = [];
    const that = this;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
      m.isTop == '1' && btnArr.length < 4 && btnArr.push(
        <Button
          ecId={`${ecId}_Button@j15m6p@${m.type}`}
          type={m.type == 'BTN_APPLY_CUSTOMER' ? 'primary' : ''}
          disabled={m.isControl == '1' && isDisabled}
          onClick={() => {
            const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
            if (m.type == 'BTN_APPLY_CUSTOMER') {
              highSeasListStore.applyCustomer(toJS(selectedRowKeys));
            }
          }}
        >

          {m.menuName}
        </Button>,
      );
    });
    return btnArr;
  }

    getColumns = (columns) => {
      const that = this;
      const { highSeasListStore } = this.props;
      columns.forEach((c) => {
        if (c.dataIndex == 'seasFlag') {
          c.render = function (text, record) {
            return (<div style={{ color: `${record.seasFlag == '1' ? 'green' : 'red'}` }}>
              {record.seasFlagspan}
            </div>);
          };
        } else {
          c.render = function (text, record) {
            const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
            return <span dangerouslySetInnerHTML={{ __html: valueSpan }} />;
          };
        }
      });
      return columns;
    }

    onEnterSearch=() => {
      const { highSeasListStore } = this.props;
      highSeasListStore.doSearch();
    }
}


export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@6gn5a3`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(HighSeasList);
